package com.repair.system.service;

import com.repair.system.entity.CaseLibrary;
import com.repair.system.repository.CaseLibraryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class CaseLibraryService {
    private final CaseLibraryRepository caseLibraryRepository;
    
    public List<CaseLibrary> getAllCases() {
        return caseLibraryRepository.findAll();
    }
    
    public CaseLibrary getCaseById(Long id) {
        return caseLibraryRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("案例不存在"));
    }
    
    public CaseLibrary saveCase(CaseLibrary caseLibrary) {
        if (caseLibrary.getCaseNumber() == null || caseLibrary.getCaseNumber().isEmpty()) {
            caseLibrary.setCaseNumber("C" + String.format("%06d", caseLibraryRepository.count() + 1));
        }
        return caseLibraryRepository.save(caseLibrary);
    }
    
    public List<CaseLibrary> searchCases(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return caseLibraryRepository.findAll();
        }
        return caseLibraryRepository.searchByKeyword(keyword);
    }
    
    public List<CaseLibrary> getCasesByDevice(String deviceName) {
        return caseLibraryRepository.findByDeviceNameContainingIgnoreCase(deviceName);
    }
    
    public List<CaseLibrary> getCasesByDifficulty(String difficulty) {
        return caseLibraryRepository.findByDifficultyLevel(difficulty);
    }
}
